package Util::Renren::Authenticate;
use Moose;
use namespace::autoclean;
use JSON;
use WWW::Curl::Easy;
use HTTP::Response;
use Digest::MD5 qw(md5_hex);
use URI::Escape;

sub get_userinfo {
	my ($self, $code, $renren_app_key, $renren_secret_key, $renren_redirect_uri, $renren_oauth_uri) = @_;
	my %sysParams;
	$sysParams{"method"} = "Users.getInfo";
	$sysParams{"v"} = "1.0";
        my $time = `date +"%Y-%m-%d %H:%M:%S"`;
        chomp($time);
        $sysParams{"call_id"} = $time;
	my %resData;
	my $post_fields = "grant_type=authorization_code&client_id=$renren_app_key&redirect_uri=$renren_redirect_uri&client_secret=$renren_secret_key&code=$code";
	$resData{"post_fields"} = $post_fields;
	my $curl = WWW::Curl::Easy->new;
	$curl->setopt(CURLOPT_HEADER,1);
	$curl->setopt(CURLOPT_POSTFIELDS, $post_fields);
	$curl->setopt(CURLOPT_URL, $renren_oauth_uri);

	my $response;
	$curl->setopt(CURLOPT_WRITEDATA,\$response);

	my $retcode = $curl->perform;
	$resData{"retcode"} = $retcode;
	$resData{"error"} = $curl->strerror($retcode);
	$resData{"errorbuf"} = $curl->errbuf;
	if ($retcode == 0) {
		$response = HTTP::Response->parse($response);
		my $xml = $response->decoded_content;
		my $json = from_json($xml);
		$resData{"headurl"} = "zhou";
		$sysParams{"access_token"} = $json->{'access_token'};
		$resData{'code'} = 0;
		
		$resData{"access_token"} = $sysParams{"access_token"};
		$resData{"username"} = $json->{'user'}->{'name'};
		$resData{"renren_id"} = $json->{'user'}->{'id'};
	} else {
			$resData{'code'} = 1;
	}
	return \%resData;
}
__PACKAGE__->meta->make_immutable;

1;
